const app = getApp()

let observer = require("../../common/lib/observer").observer
let store = require("ble_test_store").store


function inArray(arr, key, val) {
	for (let i = 0; i < arr.length; i++) {
		if (arr[i][key] === val) {
			return i;
		}
	}
	return -1;
}

// ArrayBuffer转16进制字符串示例
function ab2hex(buffer) {
	var hexArr = Array.prototype.map.call(
		new Uint8Array(buffer),
		function (bit) {
			return ('00' + bit.toString(16)).slice(-2)
		}
	)
	return hexArr.join('');
}

// 正确，保留
function ab2str(buf) {
	return String.fromCharCode.apply(null, new Uint8Array(buf));
}
// 正确，暴露
function str2ab(str) {
	var buf = new ArrayBuffer(str.length * 2); // 每个字符占用2个字节
	var bufView = new Uint16Array(buf);
	for (var i = 0, strLen = str.length; i < strLen; i++) {
		bufView[i] = str.charCodeAt(i);
	}
	return buf;
}


Page(observer({
	props: {
		store: new store()
	},
	data: {
		devices: [],
		connected: false,
		chs: [],
	},
	onShow() {
		this.show_msg("on show")
	},
	show_msg(msg) {
		this.props.store.info += JSON.stringify(msg) + '\n\n';
	},
	// 初始化蓝牙适配器
	openBluetoothAdapter() {
		wx.openBluetoothAdapter({
			success: (res) => {
				console.log('openBluetoothAdapter success', res)
				this.show_msg("初始化蓝牙成功")
				this.startBluetoothDevicesDiscovery()
			},
			fail: (res) => {
				this.show_msg("初始化蓝牙：失败")
				if (res.errCode === 10001) {
					// 监听蓝牙适配器状态变化事件
					wx.onBluetoothAdapterStateChange(function (res) {
						console.log('onBluetoothAdapterStateChange', res)
						if (res.available) {
							this.startBluetoothDevicesDiscovery()
						}
					})
				}
			}
		})
	},
	// 获取本机蓝牙适配器状态
	getBluetoothAdapterState() {
		wx.getBluetoothAdapterState({
			success: (res) => {
				this.show_msg("获取本机蓝牙状态" + res)
				console.log('getBluetoothAdapterState', res)
				if (res.discovering) {
					this.onBluetoothDeviceFound()
				} else if (res.available) {
					this.startBluetoothDevicesDiscovery()
				}
			}
		})
	},
	// 开始搜索附近的蓝牙外围设备
	startBluetoothDevicesDiscovery() {
		this.show_msg("开始搜索周边设备")
		if (this._discoveryStarted) {
			return
		}
		this._discoveryStarted = true
		wx.startBluetoothDevicesDiscovery({
			service: ['6880d7e7-93ba-4fdf-8940-31226ab93ac6'],
			allowDuplicatesKey: true,
			success: (res) => {
				this.show_msg(res)
				console.log('startBluetoothDevicesDiscovery success', res)
				this.onBluetoothDeviceFound()
			},
		})
	},
	// 获取已经发现的设备信息
	get_blue_dev_info() {
		this.show_msg("获取已发现设备信息")
		wx.getBluetoothDevices({
			success: (res) => {
				this.show_msg(res)
			}
		})	
	},
	// 停止搜索附近的蓝牙外围设备
	stopBluetoothDevicesDiscovery() {
		wx.stopBluetoothDevicesDiscovery()
	},
	// 监听搜索新设备事件
	onBluetoothDeviceFound() {
		wx.onBluetoothDeviceFound((res) => {
			res.devices.forEach(device => {
				if (!device.name && !device.localName) {
					return
				}
				const foundDevices = this.data.devices
				const idx = inArray(foundDevices, 'deviceId', device.deviceId)
				const data = {}
				if (idx === -1) {
					data[`devices[${foundDevices.length}]`] = device
				} else {
					data[`devices[${idx}]`] = device
				}
				this.setData(data)
			})
		})
	},
	// 连接低功耗蓝牙设备
	createBLEConnection(e) {
		this.show_msg("连接低功耗设备")
		const ds = e.currentTarget.dataset
		const deviceId = ds.deviceId
		const name = ds.name
		wx.createBLEConnection({
			deviceId,
			success: (res) => {
				this.show_msg(res)
				this.setData({
					connected: true,
					name,
					deviceId,
				})
				this.getBLEDeviceServices(deviceId)
			}
		})
		this.stopBluetoothDevicesDiscovery()
	},
	// 断开与低功耗蓝牙设备的连接
	closeBLEConnection() {
		wx.closeBLEConnection({
			deviceId: this.data.deviceId
		})
		this.setData({
			connected: false,
			chs: [],
			canWrite: false,
		})
	},
	// 获取蓝牙设备的所有service服务器
	getBLEDeviceServices(deviceId) {
		this.show_msg("获取蓝牙设备的所有service")
		wx.getBLEDeviceServices({
			deviceId,
			success: (res) => {
				this.show_msg(res)
				for (let i = 0; i < res.services.length; i++) {
					if (res.services[i].isPrimary) {
						this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid)
						return
					}
				}
			}
		})
	},
	
	// 获取蓝牙设备所有characteristic 特征值
	getBLEDeviceCharacteristics(deviceId, serviceId) {
		this.show_msg("获取设备所有特征值")
		wx.getBLEDeviceCharacteristics({
			deviceId,
			serviceId,
			success: (res) => {
				this.show_msg(res)
				console.log('getBLEDeviceCharacteristics success', res.characteristics)
				for (let i = 0; i < res.characteristics.length; i++) {
					let item = res.characteristics[i]
					this.show_msg("逐个显示")
					this.show_msg(item)
					if (item.properties.read) {
						// 读取低功耗蓝牙设备的特征值的二进制数值
						wx.readBLECharacteristicValue({
							deviceId,
							serviceId,
							characteristicId: item.uuid,
							// success(res) {
							// 	this.show_msg(res)
							// }
						})
					}
					if (item.properties.write) {
						this.setData({
							canWrite: true
						})
						this._deviceId = deviceId
						this._serviceId = serviceId
						this._characteristicId = item.uuid
						this.writeBLECharacteristicValue()
					}
					if (item.properties.notify || item.properties.indicate) {
						// 启用低功耗蓝牙设备的特征值变化的notify功能
						wx.notifyBLECharacteristicValueChange({
							deviceId,
							serviceId,
							characteristicId: item.uuid,
							state: true,
						})
					}
				}
			},
			fail(res) {
				console.error('getBLEDeviceCharacteristics', res)
			}
		})
		// 操作之前先监听，保证第一时间获取数据
		// 监听低功耗蓝牙设备的特征值变化
		wx.onBLECharacteristicValueChange((characteristic) => {
			// 显示信息，正确的方法
			// this.show_msg(ab2str(characteristic.value))
			const idx = inArray(this.data.chs, 'uuid', characteristic.characteristicId)
			const data = {}
			if (idx === -1) {
				data[`chs[${this.data.chs.length}]`] = {
					uuid: characteristic.characteristicId,
					value: ab2hex(characteristic.value)
				}
				
			} else {
				data[`chs[${idx}]`] = {
					uuid: characteristic.characteristicId,
					value: ab2hex(characteristic.value)
				}
			}
			// data[`chs[${this.data.chs.length}]`] = {
			//   uuid: characteristic.characteristicId,
			//   value: ab2hex(characteristic.value)
			// }
			this.setData(data)

		})
		wx.readBLECharacteristicValue({
			deviceId,
			serviceId,
			characteristicId: item.uuid,
			success(res) {
				this.show_msg(res)
			}
		})
	},
	// 向低功耗蓝牙设备特征值中写入二进制数据
	writeBLECharacteristicValue() {
		// 向蓝牙设备发送一个0x00的16进制数据
		let buffer = new ArrayBuffer(1)
		let dataView = new DataView(buffer)
		dataView.setUint8(0, Math.random() * 255 | 0)
		wx.writeBLECharacteristicValue({
			deviceId: this._deviceId,
			serviceId: this._deviceId,
			characteristicId: this._characteristicId,
			value: buffer,
		})
		
	},
	// 关闭蓝牙模块
	closeBluetoothAdapter() {
		wx.closeBluetoothAdapter()
		this._discoveryStarted = false
	},

	// 发送信息
	ble_send_msg() {
		this.show_msg("发送信息")
		let msg = "aabbcc"
		this.show_msg(msg)
		// this.show_msg(this._deviceId)
		this.show_msg(this._serviceId)
		// 向蓝牙设备发送一个0x00的16进制数据
		let buffer = new ArrayBuffer(1)
		let dataView = new DataView(buffer)
		dataView.setUint8(0, Math.random() * 255 | 0)
		wx.writeBLECharacteristicValue({
			deviceId: this._deviceId,
			serviceId: this._serviceId,
			characteristicId: this._characteristicId,
			value: str2ab(msg),
			// value: msg,
			success: (res) => {
				this.show_msg("成功")
				this.show_msg(res)
			},
			fail: (res) => {
				this.show_msg("失败")
				this.show_msg(res)
			}

		})
	}
}))